import { ref, onMounted, onBeforeUnmount } from 'vue'
import { toBDMapPoint } from '@/utils/mapUtil'
import storage from 'good-storage'
import { api } from '@/http/api'
import http from '@/http'
import { WAY_BILL_MAP_KEY } from '@/utils/constant'

export default function useMap() {
  const mapRef = ref()
  const previewText = ref('')

  let map: any
  let luShu: any
  let data: any
  let sendPoint: any
  let receivePoint: any
  let loadPoint: any
  let unloadPoint: any

  const fly =
    ''

  onMounted(() => {
    initMap()
  })

  onBeforeUnmount(() => {
    storage.session.remove(WAY_BILL_MAP_KEY)
    map = null
    luShu = null
  })

  function initMap() {
    data = storage.session.get(WAY_BILL_MAP_KEY)

    // loadLatitude loadLongitude 装货地纬度、经度
    // unloadLatitude unloadLongitude 卸货地纬度、经度
    // receiveLatitude receiveLongitude 收货地纬度、经度
    // sendLatitude sendLongitude 发货地纬度、经度
    sendPoint = toMapPoint({ longitude: data.sendLongitude, latitude: data.sendLatitude })
    receivePoint = toMapPoint({ longitude: data.receiveLongitude, latitude: data.receiveLatitude })
    loadPoint = toMapPoint({ longitude: data.loadLongitude, latitude: data.loadLatitude })
    unloadPoint = toMapPoint({ longitude: data.unloadLongitude, latitude: data.unloadLatitude })

    map = new BMapGL.Map('container')
    // 默认以发货点作为中心点
    map.centerAndZoom(sendPoint, 14)
    map.enableScrollWheelZoom(true) //地图的鼠标滚轮缩放
    map.addControl(new BMapGL.ZoomControl())
    map.addControl(new BMapGL.ScaleControl())
    map.setDisplayOptions({
      poiIcon: false,
      building: false //是否显示3D建筑物
    })

    drawCircle(sendPoint, data.shipCrawl, '发货地', getSendAddress())
    drawCircle(receivePoint, data.unloadCrawl, '收货地', getReceiveAddress())

    // 21: '待装货', 22: '运输中', 23: '待签收', 24: '已签收', 25: '已完成', 26: 已取消
    if (data.status === 21 || data.status === 26) {
      previewText.value = '暂无轨迹'
    } else {
      initLocation()
    }
  }

  function initLocation() {
    drawLoadMarker()
    // 不在运输中的时候才需要标注卸货点
    if (data.status !== 22) {
      drawUnloadMarker()
    }
    http({
      url: api.getBillLocation,
      method: 'post',
      data: { billId: data.id, type: 'BD09' }
    }).then(res => {
      if (res && res.length > 0) {
        const pointArray = res.map((item: any) => {
          return new BMapGL.Point(item.lng, item.lat)
        })
        drawLine(pointArray)
      } else {
        previewText.value = '轨迹异常'
      }
    })
  }

  function drawCircle(centerPoint: any, radius: number, title: string, content: string) {
    const circle = new BMapGL.Circle(centerPoint, radius, {
      strokeColor: 'red',
      strokeWeight: 3,
      strokeOpacity: 0.5,
      fillColor: '#FF6459',
      fillOpacity: 0.1
    })
    const mk = new BMapGL.Marker(centerPoint)
    map.addOverlay(mk)
    if (radius > 0) {
      map.addOverlay(circle)
    }
    const infoWindow = new BMapGL.InfoWindow(content, {
      width: 0,
      height: 0,
      title
    })
    mk.addEventListener('click', function () {
      map.openInfoWindow(infoWindow, centerPoint)
    })
  }

  function drawCurrentInfo(point: any) {
    const label = new BMapGL.Label('车辆当前位置')
    label.setStyle({
      color: 'blue',
      borderRadius: '5px',
      borderColor: '#ccc',
      padding: '6px',
      fontSize: '14px'
    })
    map.addOverlay(label)
    label.setPosition(point)
    // label.setOffset(new BMapGL.Size(30, 30)) // 设置文本偏移量
  }

  function drawLoadMarker() {
    const icon = new BMapGL.Icon(require('@/assets/image/ic-load-mk.png'), new BMapGL.Size(35, 58))
    const marker = new BMapGL.Marker(loadPoint, { icon })
    map.addOverlay(marker)
  }

  function drawUnloadMarker() {
    const icon = new BMapGL.Icon(require('@/assets/image/ic-unload-mk.png'), new BMapGL.Size(35, 56))
    const marker = new BMapGL.Marker(unloadPoint, { icon })
    map.addOverlay(marker)
  }

  function drawLine(pointArray: Array<any>) {
    const polyline = new BMapGL.Polyline(pointArray, {
      strokeColor: '#409EFF',
      strokeWeight: 6,
      strokeOpacity: 1
    })
    map.addOverlay(polyline)
    setTimeout(() => {
      map.setViewport(pointArray)
    }, 100)

    // const label = new BMapGL.Label('当前车辆位置')
    // map.addOverlay(label)

    // polyline.addEventListener('click', function (e: any) {
    //   const { latLng } = e
    //   console.log(e)
    //   label.setPosition(new BMapGL.Point(latLng.lng, latLng.lat))
    // })

    luShu = new BMapGLLib.LuShu(map, pointArray, {
      // defaultContent: '起飞啦', // 信息窗口文案
      autoView: true, // 是否开启自动视野调整
      speed: 1000, //默认速度 米/秒
      //new BMapGL.Icon('./images/car.png', new BMapGL.Size(32, 32), { anchor: new BMapGL.Size(10, 10) })
      icon: new BMapGL.Icon(fly, new BMapGL.Size(48, 48), { anchor: new BMapGL.Size(24, 24) }),
      enableRotation: true // 是否设置marker随着道路的走向进行旋转
    })
    const endPoint = pointArray[pointArray.length - 1]

    if (data.status === 22) {
      drawDriving(endPoint, receivePoint)
      drawCurrentInfo(endPoint)
      setTimeout(() => {
        start()
      }, 100)
    }
  }

  function drawDriving(startPoint: any, endPoint: any) {
    const driving = new BMapGL.DrivingRoute(map, {
      onSearchComplete: function (res: any) {
        // BMAP_STATUS_SUCCESS: 0
        if (driving.getStatus() == 0) {
          //返回索引指定的方案。索引0表示第一条方案
          const plan = res.getPlan(0)
          let arrPois = Array<any>()
          for (let j = 0; j < plan.getNumRoutes(); j++) {
            const route = plan.getRoute(j)
            arrPois = arrPois.concat(route.getPath())
          }
          map.addOverlay(
            new BMapGL.Polyline(arrPois, {
              strokeColor: '#b3d8ff',
              strokeWeight: 6,
              strokeOpacity: 1
            })
          )
        }
      }
    })
    driving.search(startPoint, endPoint)
  }

  // 1: 发货地   2: 收货地
  function movePoint(type: number) {
    if (!sendPoint || !receivePoint) {
      return
    }
    if (type === 1) {
      map.panTo(sendPoint)
    } else {
      map.panTo(receivePoint)
    }
    setTimeout(() => {
      const zoom = map.getZoom()
      if (zoom < 14) {
        map.setZoom(14)
      }
    }, 500)
  }

  function start() {
    if (luShu) {
      luShu.start()
    }
  }

  function pause() {
    if (luShu) {
      luShu.pause()
    }
  }

  function setSpeed(val: number) {
    if (val === 0) {
      val = 1
    }
    if (luShu) {
      luShu._opts.speed = luShu._opts.speed * val
    }
  }

  function toMapPoint(point: any) {
    const bdPoint = toBDMapPoint({ lng: point.longitude, lat: point.latitude })
    return new BMapGL.Point(bdPoint.lng, bdPoint.lat)
  }

  function getSendAddress() {
    const { sendProvinceName, sendCityName, sendCountyName, sendDetailAddress } = data
    return sendProvinceName + sendCityName + sendCountyName + sendDetailAddress
  }

  function getReceiveAddress() {
    const { receiveProvinceName, receiveCityName, receiveCountyName, receiveDetailAddress } = data
    return receiveProvinceName + receiveCityName + receiveCountyName + receiveDetailAddress
  }

  return {
    mapRef,
    previewText,
    movePoint,
    start,
    pause,
    setSpeed
  }
}
